<!--
 * @Author: 赵克强 huohuo625@163.com
 * @Date: 2024-11-28 17:42:05
 * @LastEditors: 赵克强 huohuo625@163.com
 * @LastEditTime: 2024-12-03 14:49:37
 * @FilePath: \bpm-platform-ui\src\views\app\appInfo\components\detail\processModel\conditionalComponent.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
    <el-dialog title="流转条件" :visible.sync="open" width="50%" :before-close="close" append-to-body destroy-on-close>
        <div v-loading="loading">
            <el-form ref="form" :model="form" label-width="100px" v-if="isRender">
                <div v-for="(c, i) in form.conditionalList" :key="i">
                    <el-card shadow="never" style="margin-bottom:20px">
                        <div slot="header" class="clearfix">
                            <span>流转条件组</span>
                            <el-button type="text" size="small" style="float: right;" @click="handleOperate('3', i)"
                                v-if="i === 0">添加</el-button>
                            <el-button type="text" size="small" style="float: right;color:red"
                                @click="handleOperate('4', i)" v-else>刪除</el-button>
                        </div>
                        <el-row :gutter="20" v-for="(val, index) in c.conditionalItem" :key="index">
                            <el-col :span="8">
                                <el-form-item label="表单字段">
                                    <el-select v-model="val.field.value" placeholder="请选择" filterable
                                        @change="(value) => handleChange(value, '1', index, i)">
                                        <el-option :label="item.options.label" :value="item.options.name"
                                            v-for="item in list" :key="item.id" :disabled="item.disabled"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="操作符">
                                    <el-select v-model="val.operator" placeholder="请选择"
                                        @change="(value) => handleChange(value, '2', index, i)">
                                        <el-option label="等于" value="1"></el-option>
                                        <el-option label="不等于" value="2"></el-option>
                                        <el-option label="大于" value="3"
                                            :disabled="disabledArr.includes(val.field.type)"></el-option>
                                        <el-option label="大于等于" value="4"
                                            :disabled="disabledArr.includes(val.field.type)"></el-option>
                                        <el-option label="小于" value="5"
                                            :disabled="disabledArr.includes(val.field.type)"></el-option>
                                        <el-option label="小于等于" value="6"
                                            :disabled="disabledArr.includes(val.field.type)"></el-option>
                                        <el-option label="为空" value="7"></el-option>
                                        <el-option label="不为空" value="8"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8" v-if="!['7', '8'].includes(val.operator)">
                                <el-form-item label="结果值">
                                    <el-select v-model="val.result" placeholder="请选择" filterable
                                        v-if="disabledArr.includes(val.field.type)">
                                        <el-option :label="item.label" :value="item.value"
                                            v-for="item in val.field.optionItems"></el-option>
                                    </el-select>
                                    <el-input v-model="val.result" v-else></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="2">
                                <el-button type="primary" icon="el-icon-plus" size="small" circle v-if="index === 0"
                                    @click="handleOperate('1', index, i)"></el-button>
                                <el-button type="danger" icon="el-icon-delete" size="small" circle v-else
                                    @click="handleOperate('2', index, i)"></el-button>
                            </el-col>
                            <el-col :span="6" v-if="val.isShowLogicalOperator">
                                <el-form-item label="逻辑操作符">
                                    <el-select v-model="val.logicalOperator" placeholder="请选择">
                                        <el-option label="或" value="1"></el-option>
                                        <el-option label="且" value="2"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-card>
                    <el-row>
                        <el-col :span="6" v-if="c.isShowLogicalOperator">
                            <el-form-item label="逻辑操作符">
                                <el-select v-model="c.logicalOperator" placeholder="请选择">
                                    <el-option label="或" value="1"></el-option>
                                    <el-option label="且" value="2"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </div>
            </el-form>

        </div>
        <span slot="footer" class="dialog-footer">
            <el-button @click="close">取 消</el-button>
            <el-button type="primary" @click="submit">确 定</el-button>
        </span>
    </el-dialog>
</template>
   
<script>
import { listData } from '@/api/system/dict/data.js'
import { appDictDataList } from '@/api/app/dataDict.js'
import { getProcessRoute } from "@/api/workflow/model";

export default {
    props: {
        open: {
            type: Boolean,
            default: false
        },
        close: {
            type: Function,
            default: () => { }
        },
        updateFlowCondition: {
            type: Function,
            default: () => { }
        },
        formlist: {
            type: Array,
            default: () => []
        },
        id: {
            type: String,
            default: ''
        },
    },
    data() {
        return {
            form: {
                conditionalList: [{ conditionalItem: [{ field: { value: '' }, operator: '', result: '' }] }]
            },
            list: [],
            disabledArr: ['radio', 'checkbox', 'select'],
            isRender: false,
            loading:false
        };
    },
    methods: {
        async submit() {
            const data = []
            let result = ''
            for (const item of this.form.conditionalList) {
                let flag = false;
                const list = []
                for (const val of item.conditionalItem) {
                    if (!val.field.value || !val.operator) {
                        flag = true
                        this.$message.error('请完善数据后提交')
                        break
                    }
                    if (val.isShowLogicalOperator && !val.logicalOperator) {
                        flag = true
                        this.$message.error('请完善数据后提交')
                        break
                    }
                    switch (val.operator) {
                        case '1':
                            list.push('variables:get(' + `${val.field.value})== ${val.result}${val.isShowLogicalOperator ? val.logicalOperator === '1' ? '||' : '&&' : ''}`)
                            break;
                        case '2':
                            list.push('variables:get(' + `${val.field.value})!= ${val.result}${val.isShowLogicalOperator ? val.logicalOperator === '1' ? '||' : '&&' : ''}`)
                            break;
                        case '3':
                            list.push('var:gt(' + `${val.field.value})== ${val.result}${val.isShowLogicalOperator ? val.logicalOperator === '1' ? '||' : '&&' : ''}`)
                            break;
                        case '4':
                            list.push('var:gte(' + `${val.field.value})== ${val.result}${val.isShowLogicalOperator ? val.logicalOperator === '1' ? '||' : '&&' : ''}`)
                            break;
                        case '5':
                            list.push('var:lt(' + `${val.field.value})== ${val.result}${val.isShowLogicalOperator ? val.logicalOperator === '1' ? '||' : '&&' : ''}`)
                            break;
                        case '6':
                            list.push('var:lte(' + `${val.field.value})== ${val.result}${val.isShowLogicalOperator ? val.logicalOperator === '1' ? '||' : '&&' : ''}`)
                            break;
                        case '7':
                            list.push('variables:empty(' + `${val.field.value})${val.isShowLogicalOperator ? val.logicalOperator === '1' ? '||' : '&&' : ''}`)
                            break;
                        case '8':
                            list.push('variables:isNotEmpty(' + `${val.field.value})${val.isShowLogicalOperator ? val.logicalOperator === '1' ? '||' : '&&' : ''}`)
                            break;
                    } 
                } 
                let listStr = ''
                list.forEach(x => listStr += x)
                listStr = (listStr ? `(${listStr})` : listStr) + `${item.isShowLogicalOperator ? item.logicalOperator === '1' ? '||' : '&&' : ''}`
                console.log(listStr);
                data.push(listStr)
                if (flag) {
                    break
                }
                if (item.isShowLogicalOperator && !item.logicalOperator) {
                    this.$message.error('请完善数据后提交')
                    break
                }
            }
            data.forEach(x => result += x)
            result = '${' + result + '}'
            await this.updateFlowCondition(result,this.form.conditionalList)
            this.close()
        },
        async handleChange(value, type, index, i) {
            if (type === '1') {
                this.form.conditionalList[i]['conditionalItem'][index] = { field: { value }, operator: '', result: '', isShowLogicalOperator: this.form.conditionalList[i]['conditionalItem'][index].isShowLogicalOperator }
                const row = this.list.filter(item => item.options.name === value)?.[0]
                if (this.disabledArr.includes(row?.type)) {
                    let optionItems = row.options.optionItems
                    let res = null
                    if (row.options.optionDataType === '1' && row.options.dictType === '1') {
                        res = await appDictDataList({ pageSize: 999, pageNum: 1, dictType: row.options.dictUrl })
                    }
                    if (row.options.optionDataType === '1' && row.options.dictType === '2') {
                        res = await listData({ pageSize: 999, pageNum: 1, dictType: row.options.dictUrl })
                    }
                    if (res.rows?.length) {
                        res.rows.forEach(item => { item.label = item.dictLabel; item.value = item.dictValue })
                    }
                    optionItems = res.rows
                    this.$set(this.form.conditionalList[i].conditionalItem, index, { ...this.form.conditionalList[i]['conditionalItem'][index], field: { ...this.form.conditionalList[i]['conditionalItem'][index].field, type: row.type, optionDataType: row.options.optionDataType, dictType: row.options.dictType, dictUrl: row.options.dictUrl, optionItems } })

                } else {
                    this.$set(this.form.conditionalList[i].conditionalItem, index, { ...this.form.conditionalList[i]['conditionalItem'][index], field: { ...this.form.conditionalList[i]['conditionalItem'][index].field, type: row.type } })
                }
                return
            }
            if (type === '2') {
                this.$set(this.form.conditionalList[i].conditionalItem, index, { ...this.form.conditionalList[i]['conditionalItem'][index], operator: value, result: '' })
                return
            }
        },
        async handleOperate(type, index, i) {
            switch (type) {
                case '1':
                    this.form.conditionalList[i]['conditionalItem'].push({ field: { value: '' }, operator: '', result: '' })
                    this.form.conditionalList[i]['conditionalItem'].at(-2).isShowLogicalOperator = true
                    break;
                case '2':
                    this.form.conditionalList[i]['conditionalItem'].splice(index, 1)
                    this.form.conditionalList[i]['conditionalItem'].at(-1).isShowLogicalOperator = false
                    break;
                case '3':
                    this.form.conditionalList.push({ conditionalItem: [{ field: { value: '' }, operator: '', result: '' }] })
                    this.form.conditionalList.at(-2).isShowLogicalOperator = true
                    break;
                case '4':
                    this.form.conditionalList.splice(i, 1)
                    this.form.conditionalList.at(-1).isShowLogicalOperator = false
                    break;
            }
        },
        async extractDeepestWidgetList(val) {
            val.forEach((item) => {
                if (item.category !== "container" && item.merged !== false) {
                    this.list.push(item);
                } else {
                    for (let i in item) {
                        if (Object.prototype.toString.call(item[i]) === "[object Array]") {
                            this.extractDeepestWidgetList(item[i]);
                        }
                    }
                }
            });
        },
    },
    async mounted() {
        this.loading = true
        if(this.id) {
            const res  = await getProcessRoute(this.id)
            if(!!res.data) {
                this.form.conditionalList = JSON.parse(res.data)
            }
        }
        await this.extractDeepestWidgetList(this.formlist)
        const typeArr = ['number', 'radio', 'checkbox', 'select']
        this.list = this.list.filter(item => typeArr.includes(item.type))
        this.isRender = true
        this.loading = false
    },
};
</script>
   
<style scoped lang="scss"></style>
   